<template>
  <div>
    <customizeDialog
      :title="title"
      :visible="isDialog"
      :width="isDZG ? '880px' : '1200px'"
      customPadding="0px"
      top="40px"
      @update:visible="isDialog = $event"
    >
      <div class="dialog-content">
        <el-form
          ref="basicFormRef"
          :model="form"
          :rules="basicRules"
          label-width="80px"
        >
          <div style="display: flex">
            <div class="left">
              <div class="title">问题</div>
              <el-form-item label="问题类型" prop="type">
                <el-select
                  v-model="form.type"
                  placeholder=""
                  @change="handleChangeType"
                  :disabled="isDZG"
                >
                  <el-option
                    v-for="item in typeOptions"
                    :label="item"
                    :value="item"
                    :key="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="设备编号"
                prop="equipNo"
                v-if="form.topType === '设备检查问题'"
              >
                <el-select
                  v-model="form.equipNo"
                  :allow-create="true"
                  :filterable="true"
                  :disabled="isDZG"
                  placeholder=""
                >
                  <el-option
                    v-for="item in equipNoOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="隐患等级"
                prop="problemLevelId"
              >
                <el-select
                  v-model="form.problemLevelId"
                  placeholder=""
                  :disabled="isDZG"
                >
                  <el-option
                    v-for="item in projectLevelOptions"
                    :key="item.dictValue"
                    :label="item.dictText"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="问题部位"
                prop="problemPosition"
              >
                <el-input
                  v-model="form.problemPosition"
                  :disabled="isDZG"
                ></el-input>
              </el-form-item>
              <el-form-item label="问题描述" prop="remark">
                <el-input
                  v-model="form.remark"
                  :disabled="isDZG"
                  type="textarea"
                  :rows="3"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="违反条款"
                prop="securityContentInfoList"
              >
                <div class="violation">
                  <div
                    class="violation-item"
                    v-for="(
                      item, index
                    ) of form.securityContentInfoList"
                    :key="index"
                  >
                    <div class="violation-item-content">
                      {{ item.content }}
                    </div>
                    <i
                      v-if="!isDZG"
                      class="el-icon-error"
                      @click="
                        handleRemoveViolation(index, item)
                      "
                    ></i>
                  </div>
                </div>
              </el-form-item>
              <el-form-item
                label="问题图片"
                prop="problemFileList"
              >
                <UploadVue
                  class="file-upload"
                  v-model="form.problemFileList"
                  :showFileList="false"
                  :showProgress="true"
                  uploadUrl="/fillin/security/upload"
                  :formData="{
                    projectId: projectId
                  }"
                  :disabled="isDZG"
                />
                <div class="process-img">
                  <div
                    class="process-img-item"
                    v-for="(
                      img, index
                    ) of form.problemFileList"
                    :key="index"
                  >
                    <el-image
                      :src="
                        getImage(
                          img.fileId ||
                            img.response.data ||
                            img.extra.fileId
                        )
                      "
                      :preview-src-list="
                        form.problemFileList.map((item) =>
                          getImage(
                            item.fileId ||
                              item.response.data ||
                              item.extra.fileId
                          )
                        )
                      "
                    />
                    <i
                      v-if="!isDZG"
                      class="el-icon-error"
                      @click="deleteProblemImg(index)"
                    ></i>
                  </div>
                </div>
              </el-form-item>
            </div>
            <div class="left" v-if="isDZG">
              <div class="title">整改</div>
              <el-form-item
                label="整改措施"
                prop="reformMeasure"
              >
                <el-input
                  v-model="form.reformMeasure"
                  type="textarea"
                  :rows="3"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="整改图片"
                prop="changeFileList"
              >
                <UploadVue
                  class="file-upload"
                  v-model="form.changeFileList"
                  :showFileList="false"
                  :showProgress="true"
                  uploadUrl="/fillin/security/upload"
                  :formData="{
                    projectId: projectId
                  }"
                />
                <div class="process-img">
                  <div
                    class="process-img-item"
                    v-for="(
                      img, index
                    ) of form.changeFileList"
                    :key="index"
                  >
                    <el-image
                      :src="
                        getImage(
                          img.fileId ||
                            img.response.data ||
                            img.extra.fileId
                        )
                      "
                      :preview-src-list="
                        form.changeFileList.map((item) =>
                          getImage(
                            item.fileId ||
                              item.response.data ||
                              item.extra.fileId
                          )
                        )
                      "
                    />
                    <i
                      class="el-icon-error"
                      @click="deleteChangeImg(index)"
                    ></i>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div class="right table-wrapper" v-if="!isDZG">
          <div class="title">选择违反条款</div>
          <div class="search_header">
            <div class="search_header_left">
              <el-button
                icon="el-icon-plus"
                @click="handleAddContent"
              >
                新增条款</el-button
              >
            </div>
            <div class="search_header_right">
              <el-input
                placeholder="请输入条款内容"
                clearable
                v-model="parameter.keywords"
                @input="search"
                style="width: auto !important"
              >
                <span
                  slot="suffix"
                  style="display: inline-block"
                  v-show="!parameter.keywords"
                >
                  <Icon
                    title="搜索"
                    name="sousuo"
                    color="#A7ADB5"
                    font-size="20"
                  />
                </span>
              </el-input>
            </div>
          </div>
          <el-table
            ref="tableRef"
            :data="projectList"
            :header-cell-style="{
              background: '#F2F6FB ',
              color: ' #6B767D'
            }"
            :row-class-name="tableRowClassName"
            v-loading="loading"
            @select-all="handleSelectionChange"
            @select="handleSelect"
          >
            <el-table-column
              type="selection"
              width="55"
            ></el-table-column>
            <el-table-column
              label="规范条款"
              prop="content"
              align="left"
            ></el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="updateProject(scope.row)"
                  style="color: #00baff; font-weight: 400"
                  >编辑</el-button
                >
                <el-button
                  @click="deleteProject(scope.row)"
                  type="text"
                  style="color: #ff5b5b; font-weight: 400"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-pagination" v-if="total">
            <el-pagination
              background
              layout="prev, pager, next"
              :page-size="parameter.pageSize"
              @current-change="pageChange"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
      <template slot="footer">
        <el-button
          :loading="btnLoading"
          @click="handleCancel"
          >取 消</el-button
        >
        <el-button
          :loading="btnLoading"
          type="primary"
          @click="handleSumbit"
          >确 定</el-button
        >
      </template>
    </customizeDialog>
    <!-- 条款 -->
    <termDialog ref="termRef" @success="getList" />
  </div>
</template>

<script>
import customizeDialog from '@/components/checkHistory/customizeDialog'
import UploadVue from '@/components/upload'
import termDialog from './termDialog.vue'
import {
  securityFileUrl,
  queryContentList,
  addProblemInfo,
  deleteContentInfo,
  queryProblemNoList
} from '@/api/reportManagement'
import Icon from '@/components/icon'

export default {
  name: 'addDialog',
  components: {
    customizeDialog,
    UploadVue,
    Icon,
    termDialog
  },
  props: {
    typeOptions: Array,
    projectLevelOptions: Array
  },
  data() {
    return {
      btnLoading: false,
      title: '',
      isDialog: false,
      projectId: '',
      form: {
        pkid: '',
        refId: '',
        topType: '',
        type: '',
        equipNo: '',
        problemLevelId: '',
        problemPosition: '',
        remark: '',
        violationRegulations: '',
        problemFileList: [],
        reformMeasure: '',
        changeFileList: [],
        securityContentInfoList: []
      },
      basicRules: {
        type: [
          {
            required: true,
            message: '请选择问题类型',
            trigger: 'blur'
          }
        ],
        equipNo: [
          {
            required: true,
            message: '请输入设备编号',
            trigger: 'blur'
          }
        ],
        problemLevelId: [
          {
            required: true,
            message: '请选择隐患等级',
            trigger: 'blur'
          }
        ],
        problemPosition: [
          {
            required: true,
            message: '请输入问题部位',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入问题描述',
            trigger: 'blur'
          }
        ],
        securityContentInfoList: [
          {
            required: true,
            message: '请选择违法条款',
            trigger: 'blur'
          }
        ],
        problemFileList: [
          {
            required: true,
            message: '请上传问题图片',
            trigger: 'blur'
          }
        ],
        reformMeasure: [
          {
            required: true,
            message: '请输入整改措施',
            trigger: 'blur'
          }
        ],
        changeFileList: [
          {
            required: true,
            message: '请上传整改图片',
            trigger: 'blur'
          }
        ]
      },

      equipNoOptions: [],

      projectList: [],
      total: 0,
      parameter: {
        pageSize: 5,
        pageIndex: 1,
        topType: '',
        type: '',
        keywords: ''
      },
      loading: false,

      isDZG: false
    }
  },
  computed: {},
  mounted() {},
  methods: {
    async getNoList() {
      let res = await queryProblemNoList()
      this.equipNoOptions = res.data
    },
    // 展示图片
    getImage(pkid) {
      return securityFileUrl(pkid)
    },
    show(title, refId, projectId, topType, detail, isZG) {
      this.reset()
      this.title = title
      this.form.refId = refId
      this.form.topType = topType
      this.parameter.topType = topType
      this.projectId = projectId
      this.isDZG = isZG
      if (detail.pkid) {
        this.form = Object.assign(this.form, detail)
        if (!this.isDZG) {
          this.parameter.type = detail.type
          this.search()
        }
      }
      if (topType === '设备检查问题') {
        this.getNoList()
      }
      this.isDialog = true
    },
    reset() {
      this.form = {
        pkid: '',
        refId: '',
        topType: '',
        type: '',
        equipNo: '',
        problemLevelId: '',
        problemPosition: '',
        remark: '',
        violationRegulations: '',
        problemFileList: [],
        reformMeasure: '',
        changeFileList: [],
        securityContentInfoList: []
      }
      this.projectList = []
      this.total = 0
      this.parameter.pageIndex = 1
    },
    initData() {
      this.form = {}
    },
    handleCancel() {
      this.initData()
      this.isDialog = false
    },
    handleSumbit() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          this.btnLoading = true
          let formData = JSON.parse(
            JSON.stringify(this.form)
          )
          // 问题图片
          const problemFileList = []
          this.form.problemFileList.forEach((file) => {
            problemFileList.push({
              problemId: file.extra
                ? file.extra.problemId
                : file.problemId,
              type: file.extra
                ? file.extra.type
                : file.type,
              pkid: file.pkid,
              fileId: file.fileId || file.response.data
            })
          })

          // 整改图片
          const changeFileList = []
          this.form.changeFileList.forEach((file) => {
            changeFileList.push({
              problemId: file.extra
                ? file.extra.problemId
                : file.problemId,
              type: file.extra
                ? file.extra.type
                : file.type,
              pkid: file.pkid,
              fileId: file.fileId || file.response.data
            })
          })

          // 条款
          const violationRegulations = []
          this.form.securityContentInfoList.forEach(
            (item) => {
              violationRegulations.push(item.pkid)
            }
          )

          formData.problemFileList = problemFileList
          formData.changeFileList = changeFileList
          formData.violationRegulations =
            violationRegulations.join(',')
          delete formData.securityContentInfoList

          addProblemInfo(formData).then((res) => {
            if (res.success) {
              this.$message.success('保存成功')
              this.$emit('refresh')
              this.isDialog = false
            } else {
              this.$message.error(res.message)
            }
            this.btnLoading = false
          })
        }
      })
    },

    // 切换问题类型
    handleChangeType(val) {
      this.form.securityContentInfoList = []
      this.parameter.type = val
      this.search()
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    // 获取条款列表
    getList() {
      this.loading = true
      queryContentList(this.parameter).then((res) => {
        if (res.success) {
          this.total = res.data.count
          this.projectList = res.data.list
          this.$nextTick(() => {
            this.form.securityContentInfoList.forEach(
              (item) => {
                const rows = this.projectList.filter(
                  (i) => i.pkid === item.pkid
                )
                if (rows.length > 0) {
                  this.$refs.tableRef.toggleRowSelection(
                    rows[0],
                    true
                  )
                }
              }
            )
          })
        }
        this.loading = false
      })
    },
    search() {
      this.parameter.pageIndex = 1
      this.getList()
    },
    pageChange(page) {
      this.parameter.pageIndex = page
      this.getList()
    },
    // 全选列表
    handleSelectionChange(selection) {
      if (
        selection.length !== 0 &&
        selection.length !== this.projectList.length
      ) {
        return
      }
      this.projectList.forEach((item) => {
        let index = -1
        for (
          let i = 0;
          i < this.form.securityContentInfoList.length;
          ++i
        ) {
          if (
            this.form.securityContentInfoList[i].pkid ===
            item.pkid
          ) {
            index = i
            break
          }
        }
        if (selection.length === 0 && index !== -1) {
          this.form.securityContentInfoList.splice(index, 1)
        } else if (selection.length !== 0 && index === -1) {
          this.form.securityContentInfoList.push(item)
        }
      })
    },
    // 单选列表
    handleSelect(selection, row) {
      let index = -1
      for (
        let i = 0;
        i < this.form.securityContentInfoList.length;
        ++i
      ) {
        if (
          this.form.securityContentInfoList[i].pkid ===
          row.pkid
        ) {
          index = i
          break
        }
      }
      if (index !== -1) {
        this.form.securityContentInfoList.splice(index, 1)
      } else {
        this.form.securityContentInfoList.push(row)
      }
    },
    // 移除条款
    handleRemoveViolation(index, item) {
      this.form.securityContentInfoList.splice(index, 1)
      this.$refs.tableRef.toggleRowSelection(item, false)
    },
    // 删除项目
    deleteProject(row) {
      this.$confirm(
        '此操作将永久删除该条款，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteContentInfo(row.pkid).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.getList()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch((error) => {
          this.$message.info('已取消删除')
        })
    },
    // 条款编辑弹窗
    handleAddContent() {
      if (!this.form.type) {
        this.$message.warning('请先选择问题类型')
        return
      }
      this.$refs.termRef.show('新增条款', {
        topType: this.form.topType,
        type: this.form.type
      })
    },
    // 条款编辑
    updateProject(item) {
      this.$refs.termRef.show(
        '编辑条款',
        JSON.parse(JSON.stringify(item))
      )
    },
    // 删除问题图片
    deleteProblemImg(index) {
      this.form.problemFileList.splice(index, 1)
    },
    deleteChangeImg(index) {
      this.form.changeFileList.splice(index, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/table.scss';
::v-deep {
  .el-dialog__header {
    background: #597182;
    font-size: 16px;
    .el-dialog__title {
      color: #ffffff;
    }
  }
  .el-form-item {
    width: 100%;
  }
}
.dialog-content {
  display: flex;
  // min-height: 800px;
  .title {
    width: 100%;
    color: #4c565c;
    line-height: 18px;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
    position: relative;
    box-sizing: border-box;
    padding: 0 0 0 11px;
    line-height: 16px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;

    &::before {
      content: '';
      width: 4px;
      height: 16px;
      background: linear-gradient(180deg, #40ebff, #bcf8ff);
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .left {
    width: 440px;
    border-right: 1px solid #f1f1f1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    box-sizing: border-box;
    padding: 20px;
    ::v-deep {
      .el-form-item__label {
        line-height: 40px !important;
      }
    }
  }
  .right {
    flex: 1;
    box-sizing: border-box;
    padding: 20px;
  }
}
.cancel {
  width: 80px;
  height: 34px;
  border: 1px solid #497fa3;
  font-size: 14px;
  font-weight: 400;
  color: #497fa3;
}
.sumbit {
  width: 80px;
  height: 34px;
  background: #497fa3;
  box-shadow: 0px 0px 7px 0px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  font-size: 14px;
  font-weight: 400;
  color: #ffffff;
}

.violation {
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 10px;
  &-item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 10px;
    background-color: #f1f1f1;
    box-sizing: border-box;
    padding: 5px;
    border-radius: 5px;
    &-content {
      flex: 1;
      font-size: 14px;
      line-height: 16px;
    }
    i {
      font-size: 20px;
      color: #f56c6c;
      cursor: pointer;
      margin-left: 5px;
    }
  }
}
.process-img {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  &-item {
    width: 145px;
    height: 100px;
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    .el-image {
      width: 100%;
      height: 100%;
    }
    video {
      width: 100%;
      height: 100%;
      object-fit: fill;
    }
    .el-icon-error {
      position: absolute;
      right: 0;
      top: 0;
      color: red;
      font-size: 24px;
      cursor: pointer;
    }
  }
}
</style>
